<template>
  <div class="app-container">
    <el-form ref="form" :model="searchForm" inline label-width="80px" label-suffix=":">
      <el-form-item label="角色名称">
        <el-input v-model="searchForm.roleDesc"></el-input>
      </el-form-item>
      <el-form-item label="关键字">
        <el-input v-model="searchForm.roleName"></el-input>
      </el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button type="success" @click="handleAdd">新增</el-button>
    </el-form>
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="role_description" label="角色名"></el-table-column>
      <el-table-column prop="role_remark" label="角色备注"></el-table-column>
      <el-table-column prop="role_name" label="关键字"></el-table-column>
      <el-table-column prop="role_created_date" label="创建日期">
        <template slot-scope="scope">
          <div>{{ formatTime(scope.row.role_created_date) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="role_updated_date" label="更新日期">
        <template slot-scope="scope">
          <div>{{ formatTime(scope.row.role_updated_date) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :total="total" :current-page.sync="currentPage" @current-change="currentChange" background layout="total, prev, pager, next, jumper"></el-pagination>
    <el-dialog title="角色详情" :visible.sync="dialogVisible" width="500px" :before-close="handleClose" @open='dialogOpen'>
      <el-form ref="form" :model="dialogForm" :rules="rules" label-width="80px">
        <el-form-item label="角色名" prop="roleDesc">
          <el-input v-model="dialogForm.roleDesc"></el-input>
        </el-form-item>
        <el-form-item label="角色备注" prop="roleRemark">
          <el-input v-model="dialogForm.roleRemark"></el-input>
        </el-form-item>
        <el-form-item label="关键字" prop="roleName">
          <el-input v-model="dialogForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="权限">
          <el-tree ref="tree" :data="menu" show-checkbox node-key="name" @check-change="treeChange">
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, addRole, editRole, deleteRole } from '@/api/role'
import { getMenu } from '@/api/menu'
export default {

  data() {
    return {
      menu: [],
      editType: '',
      dialogVisible: false,
      total: 0,
      currentPage: 1,
      searchForm: {
        roleDesc: '',
        roleName: '',
      },
      dialogForm: {
        roleDesc: '',
        roleName: '',
        roleRemark: '',
        menu: [],
        id: ''
      },
      tableData: [],
      rules: {
        roleDesc: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        roleName: [{ required: true, message: '请输入角色关键字', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getData()
    this.getMenu()
  },
  methods: {
    handleSearch() {
      this.currentPage = 1
      this.getData()
    },
    handleEdit(row) {
      this.dialogVisible = true
      this.editType = 'edit'
      this.dialogForm.roleDesc = row.role_description
      this.dialogForm.roleRemark = row.role_remark
      this.dialogForm.roleName = row.role_name
      this.dialogForm.menu = row.role_menu
      this.dialogForm.id = row.role_id
      setTimeout(() => {
        this.dialogForm.menu.forEach(key => {
          if (!(this.$refs.tree.getNode(key).data?.children?.length)) {
            this.$refs.tree.setChecked(key, true, false);
          }
        })
      }, 100)
    },
    dialogOpen() {
    },
    handleAdd(row) {
      this.editType = 'add'
      this.dialogForm.roleDesc = ''
      this.dialogForm.roleRemark = ''
      this.dialogForm.roleName = ''
      this.dialogForm.menu = []
      this.dialogVisible = true

    },
    async getData() {
      const params = {
        page: this.currentPage,
        ...this.searchForm
      }
      const res = await getRoleList(params)
      if(res.code === 0) {
        this.tableData = res.data
        this.total = res.total
      }
    },
    async confirm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.dialogForm.menu = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
          const { roleDesc, roleRemark, roleName, menu } = this.dialogForm
          const params = { roleDesc, roleRemark, roleName, menu }
          let requestUrl
          if (this.editType === 'edit') {
            // 编辑
            params.id = this.dialogForm.id
            requestUrl = editRole
          } else if (this.editType === 'add') {
            // 新增
            requestUrl = addRole
          }
          const res = await requestUrl(params)
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: this.editType === 'edit' ? '修改成功' : '新增成功'
            })
            this.handleClose()
            this.getData()
          }
        }
      })
    },
    handleClose() {
      this.$refs.tree.setCheckedKeys([])
      this.dialogVisible = false
      this.dialogForm.roleDesc = ''
      this.dialogForm.roleRemark = ''
      this.dialogForm.roleName = ''
      this.dialogForm.menu = []
      this.dialogForm.id = ''
      this.editType = ''
      setTimeout(() => this.$refs.form.clearValidate(), 500)
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = deleteRole({
          id: row.role_id
        })
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
        this.getData()

      }).catch(() => {})
    },
    treeChange() {
    },
    currentChange() {
      this.getData();
    },
    async getMenu() {
      const res = await getMenu()
      if (res.code === 0) {
        this.menu = res.data
      }
    }
  }
}
</script>
